from flask import Flask, request
from flask_restful import Resource, Api
from Day08.d01_qiniu import update_image
from Day08.models import User, db

app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEY_DATABASE_URI'] = 'mysql://root:mysql@127.0.0.1:3306/toutiao'
db.init_app(app)

# 创建api对象,并关联app
api = Api(app)
# 定义视图类
class Profile(Resource):
    def patch(self):
        # 修改图片
        photo = request.files.get('photo')
        mobile = request.form.get('mobile')

        # 图片为空校验
        if not photo:
            return 'photo 不存在'

        # 上传图片
        filename = update_image(photo.read())
        user = User.query.filter(User.mobile == mobile).first()

        # 用户为空校验
        if not user:
            # 用户不存在,创建用户
            user = User(mobile= mobile, name=mobile)
            db.session.add(user)
            db.session.commit()

        # 修改用户头像
        user.profile_photo = filename
        db.session.add(user)
        db.session.commit()
        return 'http://pwb3gabzd.bkt.clouddn.com/' + user.profile_photo

api.add_resource(Profile, '/v1_0/user/photo')


if __name__ == '__main__':
    app.run(host='192.168.226.129', debug=True)
